<?php

namespace App\Http\Controllers\Admin\Customer;

use App\Exceptions\AppException;
use App\Exports\BigBagExport;
use App\Exports\BigTakeOrderExport;
use App\Exports\BigTakeOrderManifestExport;
use App\Http\Controllers\Admin\CallBack;
use App\Http\Controllers\Controller;
use App\Http\Requests\customer\NodeRequest;
use App\Models\airline\base\RouteModel;
use App\Models\lazada\NodeModel;
use App\Models\lazada\NodeRecordModel;
use App\Models\customer\PriceModel;
use App\Models\customer\ResourceModel;
use App\Models\CustomerModel;
use App\Models\FlightItemModel;
use App\Models\FlightModel;
use App\Models\lazada\ApiModel;
use App\Models\TakeOrderModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;
use App\Models\lazada\OrderModel;
use App\Models\lazada\BigBagModel;

class BigTakeOrder extends Controller
{
    use NodeRequest;

    /**
     * Notes:列表
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $take_order_sn = $request->input('take_order_sn', '');
        $start_time = $request->input('startTime', '');
        $end_time = $request->input('endTime', '');
        $des_country_id = $request->input('des_country_id', '');
//        $customer_type_id = $request->input('customer_type_id', '');
        $customer_id = $request->input('customer_id', '');
        $airline_flight_id = $request->input('airline_flight_id', '');
        $flight_status = $request->input('flight_status', '');
        $status = $request->input('status', '');


        $query = TakeOrderModel::with(['customer', 'flight', 'notify'])
            ->whereHas('customer', function($query){
                $query->where('customer_type_id', 16);
            });

        if($customer_id){
            $query = $query->where('customer_id', $customer_id);
        }

        if($take_order_sn){
            $query = $query->where('sn', 'like', '%'.$take_order_sn.'%');
        }

        if(($start_time && $end_time) || $des_country_id || $flight_status || $airline_flight_id){
            $query = $query->whereHas('flight', function($query) use ($start_time, $end_time, $des_country_id, $airline_flight_id, $flight_status){
                if($start_time && $end_time){
                    $query->whereBetween('take_off_time', [$start_time, $end_time]);
                }
                if($des_country_id){
                    $query->where('arrive_port_country_id', $des_country_id);
                }
                if($flight_status){
                    $query->where('status', $flight_status);
                }
                if($airline_flight_id){
                    $query->whereHas('flight_lines', function($query) use ($airline_flight_id){
                        $query->where('airline_flight_id', $airline_flight_id);
                    });
                }
            });
        }


        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $big_pkgs = $item->notify->count();

            $grossWeight = $item->notify->sum('bigBagWeight');
            $grossWeight = $grossWeight ?? 0;
            $grossWeight = round($grossWeight / 1000, 3);

            $storage_weight = $item->notify->sum('storage_weight');
            $storage_weight = $storage_weight ?? 0;
            $storage_weight = round($storage_weight / 1000, 3);

            $small_count = $item->notify->sum('parcelQty');

            $des_country = $item->flight->arrive_port_code ?? '';

            if($item->flight && $item->flight->items){
                $flight_lines = $item->flight->items->map(function($flight_line){
                    return [
                        'flight_number' => $flight_line->air_line->flight_number,
                        'route_name' => $flight_line->route->code,
                    ];
                });

                $flight_lines = $flight_lines->toArray();
            }else{
                $flight_lines = [];
            }


            $res = [
                'id' => $item->id,
                'customer_id' => $item->customer_id,
                'customer_name' => $item->customer->name,
                'customer_code' => $item->customer->sn,
                'take_order_sn' => $item->sn,
                'big_pkgs' => $big_pkgs,
                'grossWeight' => $grossWeight,
                'storage_weight' => $storage_weight,
//                'system_node' => $item->system_node->name_cn ?? '',
//                'platform_node' => $item->platform_node->name_cn ?? '',
                'email' => '',
                'des_country' => $des_country,
                'route_name' => array_column($flight_lines, 'route_name'),
                'flight_number' => $flight_lines ? array_column($flight_lines, 'flight_number') : $item->flight_number,
                'take_off_time' => $item->flight->take_off_time ?? '',
                'small_count' => $small_count,
                'pre_flight_number' => $item->flight_number ?? '',
                'flight_id' => $item->flight_id,
            ];
            return $res;
        });

        //统计
        $total_notify = $query->with('notify')->get();
        $total_big = 0; $total_weight = 0; $total_nums = 0;
        foreach ($total_notify as $item){
            if($item->notify){
                $total_big += $item->notify->count();
                $total_weight += $item->notify->sum('bigBagWeight');
                $total_nums += $item->notify->sum('parcelQty');
            }
        }

        $statistics = [
            'total_take_order' => $total,
            'total_big' => $total_big,
            'total_weight' => round($total_weight / 1000, 3),
            'total_nums' => $total_nums
        ];

        return $this->success(['list' => $list, 'total' => $total, 'statistics' => $statistics]);
    }

    /**
     * Notes:创建大客户提单
     * User: xiangzi
     * Date: 2025/3/10
     * Time: 上午10:42
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request) {
        $auth = $request->get('auth');
        $params = $request->all();

//        $check_res = self::add_check($params);
//        if($check_res->faild){
//            return $this->error($check_res->err);
//        }

        $find = TakeOrderModel::where('sn', $params['sn'])->first();
        if($find){
            return $this->error('提单号已存在');
        }

        $model = new TakeOrderModel();
        $model->sn = $params['sn'];
        $model->customer_id = $params['customer_id'];
        $model->created_admin_id = $auth->id;
        $model->save();

        return $this->success();
    }

    public function update(Request $request) {
        $auth = $request->get('auth');
        $params = $request->all();
        $flight_id = $request->input('flight_id',  '');
        $flight_number = $request->input('flight_number',  '');

        $find = TakeOrderModel::find($params['id']);

        if(!$find){
            return $this->error('提单不存在');
        }

        if($find->sn != $params['sn']){
            $find_check = TakeOrderModel::where('sn', $params['sn'])->first();
            if($find_check){
                return $this->error('提单号已存在');
            }
        }

//        if($flight_number){
//            $flight_find = \App\Models\airline\base\FlightModel::where('flight_number', $flight_number)->first();
//            if($flight_find){
//                $flight = FlightItemModel::where('airline_flight_id', $flight_find->id)->first();
//                if($flight){
//                    $find->flight_id = $flight->id;
//                }
//            }
//        }

        if($flight_id){
            $find->flight_id = $flight_id;
        }

        $find->sn = $params['sn'];
        $find->customer_id = $params['customer_id'];
        $find->flight_number = $flight_number ??  '';
        $find->created_admin_id = $auth->id;
        $find->save();

        return $this->success();
    }

    //获取排货信息
    public function get_flight_select(Request $request) {
        $flight_number = $request->input('flight_number',  '');

        $airline_flight = \App\Models\airline\base\FlightModel::where('flight_number', $flight_number)->first();

        $return = [];
        if($airline_flight){
            $flight_items = FlightItemModel::where('airline_flight_id', $airline_flight->id)
//                ->where('date', '>=', date('Y-m-d'))
                ->get();
            if($flight_items){
                $list = $flight_items->map(function($item) use ($flight_number) {

                    $date = $item->date ?? '';
                    if($date){
                        $d = new \DateTime($date);
                        $date = $d->format('d.M');
                    }

                    return [
                        'id' => $item->flight_id,
                        'name' => $flight_number . '/' . $date,
                    ];
                });
                $return = $list->toArray();
            }
        }

        return $this->success($return);
    }

    /**
     * Notes:未配舱航班运力列表
     * User: xiangzi
     * Date: 2025/3/17
     * Time: 上午10:56
     * @return \Illuminate\Http\JsonResponse
     */
    public function flight() {
        $flight_ids = FlightModel::with('items')->where('status', 1)->pluck('id');

        $flight = FlightItemModel::with('air_line')->whereIn('flight_id', $flight_ids)->get();

        $list = $flight->map(function($item){

            $res = [
                'id' => $item->flight_id,
                'flight_no' => $item->air_line->flight_number ?? '',
            ];
            return $res;
        });

        return $this->success($list);
    }

    public function detail(Request $request) {
        $id = $request->input('id');

        $take_order = TakeOrderModel::find($id);

        if (!$take_order) {
            return  $this->error('订单不存在');
        }

        if($take_order->flight && $take_order->flight->items){
            $flight_lines = $take_order->flight->items->map(function($flight_line){
                return [
                    'flight_number' => $flight_line->air_line->flight_number,
                    'route_name' => $flight_line->route->name,
                ];
            });
            $flight_lines = $flight_lines->toArray();
        }else{
            $flight_lines = [];
        }


//        $order_ids = $take_order->orders->pluck('id')->toArray();

        $big_bags = BigBagModel::where('take_order_id', $id)->get();

        $big_list = $big_bags->map(function($bag){
            $res = [
                'id' => $bag->id,
                'customer_name' => $bag->customer->name,
                'bigBagID' => $bag->bigBagID,
                'nums' => $bag->parcelQty,
                'grossWeight' => $bag->bigBagWeight,
                'goods_attr' => \App\Models\OrderModel::GOODS_ATTR_MAPS[$bag->cargoType],
                'warehouse_name' => $bag->warehouse->name ?? '',
                'status_text' => $bag->system_node->name ?? '',
                'created_at' => $bag->created_at->toDateTimeString(),
                'remarks'=> $bag->remarks
            ];
            return $res;
        });


        $return = [];
        $return['base_info'] = [
            'id' => $take_order->id,
            'customer_name' => $take_order->customer->name,
            'customer_code' => $take_order->customer->sn,
            'take_order_sn' => $take_order->sn,
            'take_off_time' => $take_order->flight->take_off_time ?? '',
            'flight_number' => array_column($flight_lines, 'flight_number'),
            'route_name' => array_column($flight_lines, 'route_name'),
            'status_text' => ''
        ];
        $return['big_list'] = $big_list;

        return $this->success($return);
    }


    /**
     * Notes:导入列表
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function import_info(Request $request) {
        $take_order_id = $request->input('id');
//        $page = $request->input('page', 1);
//        $limit = $request->input('limit', 20);
//        $bigBagID = $request->input('bigBagID', '');
//        $des_country_id = $request->input('des_country_id', '');
//        $warehouse_id = $request->input('warehouse_id', '');
//        $create_start = $request->input('startTime', '');
//        $create_end = $request->input('endTime', '');
//        $is_error = $request->input('is_error', '');
//        $is_lack = $request->input('is_lack', '');
//        $node_id = $request->input('node_id', '');
//        $bigBagID = $request->input('bigBagID', '');


        $take_order = TakeOrderModel::find($take_order_id);
        if (!$take_order) {
            return  $this->error('提单不存在');
        }

//        $customer_id = $take_order->customer_id;

        $flight = FlightModel::find($take_order->flight_id);

        if($flight && $flight->items){
            $flight_lines_info = $flight->items->map(function($flight_line){
                return [
                    'flight_number' => $flight_line->air_line->flight_number,
                    'route_name' => $flight_line->route->name,
                ];
            });

            $flight_lines_info = $flight_lines_info->toArray();
        }else{
            $flight_lines_info = [];
        }


        $import_big_count = BigBagModel::where('take_order_id', $take_order_id)->count();

        $flight_info = [
            'flight_number' => implode(',', array_column($flight_lines_info, 'flight_number')),
            'route_name' => implode(',', array_column($flight_lines_info, 'route_name')),
            'take_off_time' => $flight->take_off_time ?? '',
            'take_order_sn' => $take_order->sn,
            'import_big_count' => $import_big_count ?? 0
        ];

//        $query = BigBagModel::where('take_order_id', 0)
//            ->where('customer_id', $customer_id);
//
//        if($bigBagID){
//            $query = $query->where('bigBagID', $bigBagID);
//        }
//
//
//        $total = $query->count('id');
//        $items = $query
//            ->orderBy('id', 'desc')
//            ->get();
//
//
//        $list = $items->map(function($item){
//            $goods_value = $item->small->sum('price') ?? 0;
//            $goods_value = $goods_value ? round($goods_value / 1000, 2) : 0;
//
//            $res = [
//                'id' => $item->id,
//                'customer_name' => $item->customer->name ?? '',
//                'bigBagID' => $item->bigBagID,
//                'des_country_name' => $item->toLocation,
//                'order_sn' => $item->order->sn ?? '',
//                'goods_attr' => \App\Models\OrderModel::GOODS_ATTR_MAPS[$item->cargoType] ?? '',
//                'con_warehouse' => '',
//                'delivery_provider' => '',
//                'export_agent' => '',
//                'goods_value' => $goods_value,
//                'grossWeight' => round($item->bigBagWeight / 1000, 2),
//                'parcelQty' => $item->parcelQty,
//                'system_node' => $item->system_node->name_cn ?? '',
//                'created_at' => $item->created_at->toDateTimeString(),
//                'remarks' => $item->remarks,
//                'is_error' => $item->is_error,
//                'is_lack' => $item->is_lack
//            ];
//            return $res;
//        });

        return $this->success(['flight_info' => $flight_info]);
    }


    /**
     * Notes:导入列表查询
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function import_list(Request $request)
    {
        $bigBagID = $request->input('bigBagID', []);

        if(!$bigBagID){
            return $this->error('请输入大包ID');
        }

        $big_list = BigBagModel::with(['customer', 'order'])
            ->where('take_order_id', 0)
            ->whereIn('bigBagID', $bigBagID)
            ->get();

        $big_list = $big_list->map(function($bag){
            $res = [
                'id' => $bag->id,
                'customer_name' => $bag->customer->name ?? '',
                'bigBagID' => $bag->bigBagID,
                'des_country_name' => $bag->toLocation,
                'order_sn' => $bag->order->sn ?? '',
                'goods_attr' => \App\Models\OrderModel::GOODS_ATTR_MAPS[$bag->cargoType] ?? '',
                'grossWeight' => round($bag->bigBagWeight / 1000, 2),
                'parcelQty' => $bag->parcelQty,
                'created_at' => $bag->created_at->toDateTimeString(),
            ];
            return $res;
        });

        return $this->success(['list' => $big_list]);
    }

    /**
     * Notes:确认配舱
     * User: xiangzi
     * Date: 2024/11/5
     * Time: 下午3:20
     * @return \Illuminate\Http\JsonResponse
     */
    public function import(Request $request)
    {
        $ids = $request->input('ids', []);
        $take_order_id = $request->input('take_order_id');

        if(empty($ids)){
            return $this->error('请选择需要导入的大包');
        }

        $take_order = TakeOrderModel::find($take_order_id);
        if(!$take_order){
            return $this->error('提单id不能为空');
        }

        $bigbags = BigBagModel::whereIn('id', $ids)->get();
        $goods_attr = $bigbags->pluck('cargoType')->unique()->toArray();
        if(count($goods_attr) > 1){
            return $this->error('货物属性不一致');
        }
        $goods_attr = $goods_attr[0];

//        $flight_lines = $take_order->flight->items ?? [];
//
//        $route = [];
//        foreach ($flight_lines as $flight_line){
//            $route[$flight_line->destination_id] = $flight_line->route_id;
//        }

        DB::beginTransaction();
        try {
            BigBagModel::whereIn('id', $ids)->update(['take_order_id' => $take_order_id]);

            $take_order->big_pkgs = $take_order->big_pkgs + count($ids);
            $take_order->goods_attr = $goods_attr;
            $take_order->save();

//            foreach ($ids as $id){
//                $res = $this->price($id, $route, $take_order_id);
//                if(!$res['result']){
//                    DB::rollBack();
//                    return $this->error($res['msg']);
//                }
//            }

            DB::commit();

        }catch (AppException $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }


        return $this->success();

    }

    /**
     * Notes: 报价
     * User: xiangzi
     * Date: 2024/11/5
     * Time: 下午4:10
     * @return array|void
     */
    public function price($id, $route, $take_order_id)
    {
        $big_bag = BigBagModel::find($id);
        if (!$big_bag) {
            return ['result' => false, 'msg' => '大包不存在'];
        }

        $asn = OrderModel::where('bigBagID', $big_bag->bigBagID)->get();

        foreach ($asn as $item){

            if(!isset($route[$item->des_country_id])){
                return ['result' => false, 'msg' => '小包目的地国家与航线目的国家不匹配'];
            }
            $route_id = $route[$item->des_country_id];
            $price = PriceModel::where('customer_id', $big_bag->customer_id)
                ->where('route_id', $route_id)->where('goods_attr', $item->goods_attr)->first();

            if($price){
                $weight = round($item->weight/1000, 3);
                $item->currency_id = $price->currency_id;
                $item->transfer_amount = round($price->transfer_price * $weight, 3);
                $item->declare_amount = round($price->declare_price * $weight, 3);
                $item->airport_amount = round($price->airport_price * $weight, 3);
                $item->clearance_amount = round($price->clearance_price * $weight, 3);
                $item->dispatch_amount = round($price->dispatch_price * $weight, 3);
                $item->total_amount = round($item->transfer_amount + $item->declare_amount + $item->airport_amount + $item->clearance_amount + $item->dispatch_amount, 3);
                $item->take_order_id = $take_order_id;
                $item->save();
            }else{
                return ['result' => false, 'msg' => '没有找到对应的报价'];
            }
        }
        return ['result' => true];

    }

    /**
     * Notes: 提单回传状态
     * User: xiangzi
     * Date: 2024/11/5
     * Time: 下午4:09
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function take_order_status(Request $request)
    {
        $id = $request->input('id');
        $take_order = TakeOrderModel::with(['system_node'])->find($id);

        if(!$take_order){
            return $this->error('提单不存在');
        }

        $return = [
            'status' => $take_order->system_node->name_cn ?? '',
            'is_callback' => $take_order->system_node_id == $take_order->platform_node_id ? 1 : 0,
            'is_delete' => $take_order->system_node_id == $take_order->platform_node_id ? 0 : 1,
        ];

        return $this->success($return);
    }

    /**更新本地系统节点
     * Notes:
     * User: xiangzi
     * Date: 2024/11/1
     * Time: 上午10:38
     * @return \Illuminate\Http\JsonResponse
     */
    public function update_system_node(Request $request)
    {
        $auth = $request->get('auth');
        $params = $request->all();

        $validator = Validator::make($params, [
            'id' => 'required',
            'node_id' => 'required',
            'datetime' => 'required'
        ], [
            'id.required' => 'id不能为空',
//            'id.integer' => 'id必须为数字',
            'node_id.required' => '请选择节点',
            'datetime' => '请填写时间'
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        $id = $params['id'][0];

        DB::beginTransaction();
        try{

                $find = TakeOrderModel::find($id);

                if(!$find){
                    return $this->error('提单不存在');
                }

                if($params['node_id'] != $find->system_node_id + 1){
                    return $this->error('不能越节点回传');
                }

                $find->system_node_id = $params['node_id'];
                $find->save();

                //大包同步
                BigBagModel::where('take_order_id', $id)->update(['system_node_id' => $params['node_id']]);
                //小包同步
                OrderModel::where('take_order_id', $id)->update(['system_node_id' => $params['node_id']]);

                $record = new NodeRecordModel();
                $record->type = 1;
                $record->customer_id = $find->customer_id;
                $record->node_id = $params['node_id'];
                $record->take_order_id = $find->id;
                $record->take_order_sn = $find->sn;
                $record->datetime = $params['datetime'];
                $record->record_type = 3;
                $record->created_admin_id = $auth->id;
                $record->save();


            DB::commit();

        }catch (AppException $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    //未更新提单
    public function unupdate_take_order(Request $request)
    {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
//        $bigBagID = $request->input('bigBagID', '');
//        $goods_attr = $request->input('goods_attr', '');
//        $des_country_id = $request->input('des_country_id', '');
//        $node_id = $request->input('node_id', '');

        $query = TakeOrderModel::query()->with(['customer', 'system_node', 'platform_node', 'flight']);


        $query->whereColumn('system_node_id', '<>', 'platform_node_id');

        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item){
            $res = [
                'id' => $item->id,
                'customer_name' => $item->customer->name,
                'sn' => $item->sn,
                'des_country_name' => $item->flight->arrive_port_code ?? '',
                'system_node' => $item->system_node->name_cn ?? '',
                'platform_node' => $item->platform_node->name_cn ?? '',
            ];
            return $res;
        });


        return $this->success(['list' => $list, 'total' => $total]);

    }

    //回退提单状态
    public function back(Request $request)
    {
        $take_order_id = $request->input('id',  '');

        $find = TakeOrderModel::find($take_order_id);
        if(!$find){
            return $this->error('提单不存在');
        }

        if($find->system_node_id == $find->platform_node_id){
            return $this->error('提单回传，不能删除');
        }

        $find->system_node_id = $find->platform_node_id;
        $find->save();
        return $this->success();
    }

    /**
     * Notes:更新平* User: xiangzi
     * Date: 2024/11/1
     * Time: 上午10:39
     * @return \Illuminate\Http\JsonResponse
     */
    public function update_platform_node(Request $request)
    {
        $auth = $request->get('auth');


        $ids = $request->input('id',  []);

        DB::beginTransaction();
        try{
            foreach ($ids as $id){
                $find = TakeOrderModel::find($id);

                if(!$find){
                    return $this->error('提单包不存在');
                }

//                $record = new NodeRecordModel();
//                $record->type = 2;
//                $record->customer_id = $find->customer_id;
//                $record->node_id = $find->system_node_id;
//                $record->take_order_id = $find->id;
//                $record->take_order_sn = $find->sn;
//                $record->datetime = date('Y-m-d H:i:s');
//                $record->record_type = 3;
//                $record->created_admin_id = $auth->id;


//                $node = NodeModel::find($params['node_id']);
                $bigbag_ids = BigBagModel::where('take_order_id', $id)->pluck('id');

                foreach ($bigbag_ids as $bigbag_id){
                    $bigbag_find = BigBagModel::find($bigbag_id);

                    $node = NodeModel::find($bigbag_find['system_node_id']);
                    $api = ApiModel::find($node->api_id);

                    if(!$api){
                        return $this->error('节点接口不存在');
                    }

                    $record = new NodeRecordModel();
                    $record->type = 2;
                    $record->customer_id = $find->customer_id;
                    $record->node_id = $find->system_node_id;
                    $record->bigbag_id = $find->id;
                    $record->bigBagID = $find->bigBagID;
                    $record->datetime = date('Y-m-d H:i:s');
                    $record->record_type = 1;
                    $record->created_admin_id = $auth->id;

                    $call_back = new CallBack();

                    $res = $call_back->common_bigbag_callback($bigbag_find->id, $api->nodeCode, $api->activityCode);

                    if(!$res['result']){
                        $record->status = 0;
                        $record->save();
                        DB::commit();
                        return $this->error($res['msg']);
                    }

                    $bigbag_find->platform_node_id = $bigbag_find['system_node_id'];
                    $bigbag_find->save();

                    //更新小包
                    \App\Models\lazada\OrderModel::where('bigBagID',$bigbag_find->bigBagID)->update(['platform_node_id'=>$bigbag_find['system_node_id']]);

                }

//                $record->save();
                $find->platform_node_id = $find->system_node_id;
                $find->save();
            }

            DB::commit();

        }catch (AppException $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    public function export(Request $request) {
//        $take_order_sn = $request->input('take_order_sn', '');
//        $start_time = $request->input('startTime', '');
//        $end_time = $request->input('endTime', '');
//        $des_country_id = $request->input('des_country_id', '');
//        $customer_type_id = $request->input('customer_type_id', '');
//        $customer_keyword = $request->input('customer_keyword', '');
//        $airline_flight_id = $request->input('airline_flight_id', '');
//        $flight_status = $request->input('flight_status', '');
//        $status = $request->input('status', '');

        $ids = $request->input('ids',  []);


//        $query = TakeOrderModel::whereHas('customer', function($query) use ($customer_keyword, $customer_type_id){
//            $query->where('is_big', 1);
//            if($customer_type_id){
//                $query->where('customer_type_id', $customer_type_id);
//            }
//            if($customer_keyword){
//                $query->where('name', 'like', '%'.$customer_keyword.'%')->orWhere('sn', 'like', '%'.$customer_keyword.'%');
//            }
//        });
//
//        if($take_order_sn){
//            $query = $query->where('sn', 'like', '%'.$take_order_sn.'%');
//        }
//
//        if(($start_time && $end_time) || $des_country_id || $flight_status || $airline_flight_id){
//            $query = $query->whereHas('flight', function($query) use ($start_time, $end_time, $des_country_id, $airline_flight_id, $flight_status){
//                if($start_time && $end_time){
//                    $query->whereBetween('take_off_time', [$start_time, $end_time]);
//                }
//                if($des_country_id){
//                    $query->where('destination_id', $des_country_id);
//                }
//                if($flight_status){
//                    $query->where('status', $flight_status);
//                }
//                if($airline_flight_id){
//                    $query->whereHas('flight_lines', function($query) use ($airline_flight_id){
//                        $query->where('airline_flight_id', $airline_flight_id);
//                    });
//                }
//            });
//        }


        $items = TakeOrderModel::with(['customer', 'notify'])->whereIn('id', $ids)->get();

        $list = $items->map(function($item) {
            $big_pkgs = $item->notify->count();

            $grossWeight = $item->notify->sum('bigBagWeight');
            $grossWeight = $grossWeight ?? 0;
            $grossWeight = round($grossWeight / 1000, 3);

            $storage_weight = $item->notify->sum('storage_weight');
            $storage_weight = $storage_weight ?? 0;
            $storage_weight = round($storage_weight / 1000, 3);

            $small_count = $item->notify->sum('parcelQty');

            $des_country = $item->flight->arrive_port_country_name ?? '';

            if($item->flight && $item->flight->items){
                $flight_lines = $item->flight->items->map(function($flight_line){
                    return [
                        'flight_number' => $flight_line->air_line->flight_number,
                        'route_name' => $flight_line->route->code,
                    ];
                });

                $flight_lines = $flight_lines->toArray();
            }else{
                $flight_lines = [];
            }


            $res = [
                'customer_name' => $item->customer->name,
                'take_order_sn' => $item->sn,
                'big_pkgs' => $big_pkgs,
                'small_count' => $small_count,
                'grossWeight' => $grossWeight,
                'storage_weight' => $storage_weight,
                'des_country' => $des_country,
                'route_name' => implode(',', array_column($flight_lines, 'route_name')),
                'flight_number' => implode(',', array_column($flight_lines, 'flight_number')),
                'take_off_time' => $item->flight->take_off_time ?? '',
            ];
            return $res;
        });


        return Excel::download(new BigTakeOrderExport(collect($list)), '大客户提单数据.xlsx');
    }


    //提单信息回传
    public function callback(Request $request)
    {
        $auth = $request->get('auth');
        $ids  = $request->input('ids', []);

        $list = TakeOrderModel::whereIn('id', $ids)->get();

        DB::beginTransaction();
        try{
            foreach ($list as $value){

                $record = new NodeRecordModel();
                $record->type = 2;
                $record->customer_id = $value->customer_id;
                $record->node_id = 0;
                $record->take_order_id = $value->id;
                $record->take_order_sn = $value->sn;
                $record->datetime = date('Y-m-d H:i:s');
                $record->record_type = 3;
                $record->created_admin_id = $auth->id;

                $call_back = new CallBack();

                $res = $call_back->delivery_line_haul_mawb_callback($value->id);

                if(!$res['result']){
                    $record->status = 0;
                    $record->save();
                    DB::commit();
                    return $this->error($res['msg']);
                }

                TakeOrderModel::where('id', $value->id)->update(['is_callback' => 1]);
                $record->save();

            }

            DB::commit();

        }catch (AppException $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    /**
     * 解绑
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function unbind(Request $request)
    {
        $id = $request->input('id',  '');

        $bigbag = BigBagModel::find($id);

        if(!$bigbag){
            return $this->error('大包不存在');
        }

        $bigbag->take_order_id = 0;
        $bigbag->save();

        $take_order = TakeOrderModel::find($bigbag->take_order_id);
        if($take_order){
            $take_order->big_pkgs -= 1;
            $take_order->save();
        }

        return $this->success();
    }


    /**
     * 批量解绑
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function unbind_batch(Request $request)
    {
        $ids = $request->input('ids',  []);

        $bigBag = BigBagModel::find($ids[0]);
        if($bigBag){
            $take_order = TakeOrderModel::find($bigBag->take_order_id);
            if($take_order){
                $take_order->big_pkgs -= count($ids);
                $take_order->save();
            }
        }

        BigBagModel::whereIn('id', $ids)->update(['take_order_id' => 0]);

        return $this->success();
    }

    public function manifest(Request $request)
    {
        $take_order_ids = $request->input('ids', []);

        $data = [];
        foreach ($take_order_ids as $take_order_id){
            $take_order = TakeOrderModel::find($take_order_id);
            if(!$take_order){
                return $this->error('提单不存在');
            }

            $bigbagID = $take_order->notify->pluck('bigBagID');

            $orders = OrderModel::whereIn('bigBagID', $bigbagID)
                ->select('orderCode', 'receiver', 'sender', 'trackingNumber', 'bigBagID', 'fromLocation', 'toLocation', 'parcel', 'features')
                ->get();

            $transportNo = $take_order->flight_number;
            $sn = $take_order->sn;

//            $flight = $take_order->flight;
//            if($flight){
//                $item = $flight->items->first();
//                $transportNo = $item->air_line->flight_number ??  '';
//            }

            $list = $orders->map(function($order) use ($transportNo, $sn) {
                $receiver = json_decode($order->receiver,  true);
                $receiver_address = ''; $receiver_detailAddress = '';
                if($receiver['address']){
                    $receiver_detailAddress = $receiver['address']['detailAddress'] ??  '';
                    if(isset($receiver['address']['detailAddress'])){
                        unset($receiver['address']['detailAddress']);
                    }

                    $receiver_address = implode(' ', $receiver['address']);
                }

                $sender = json_decode($order->sender,  true);
                $sender_address = ''; $sender_detailAddress = '';
                if($sender['address']){
                    $sender_detailAddress = $sender['address']['detailAddress'] ??  '';
                    if(isset($sender['address']['detailAddress'])){
                        unset($sender['address']['detailAddress']);
                    }
                    $sender_address = implode(' ', $sender['address']);
                }

                $base_data = [
                    'orderCode' => $order->orderCode,
                    'trackingNumber' => $order->trackingNumber,
                    'bigBagID' => $order->bigBagID,
                    'transportNo' => $transportNo,
                    'mawbNumber' => $sn,
                    'fromLocation' => $order->fromLocation,
                    'toLocation' => $order->toLocation,
                    'receiver_name' => $receiver['name'] ??  '',
                    'receiver_phone' => $receiver['phone'] ??  '',
                    'receiver_mobile' => $receiver['mobile'] ??  '',
                    'receiver_email' => $receiver['email'] ??  '',
                    'receiver_zipCode' => $receiver['zipCode'] ??  '',
                    'receiver_address' => $receiver_address,
                    'receiver_detailAddress' => $receiver_detailAddress,
                    'sender_name' => $sender['name'] ??  '',
                    'sender_phone' => $sender['phone'] ??  '',
                    'sender_mobile' => $sender['mobile'] ??  '',
                    'sender_email' => $sender['email'] ??  '',
                    'sender_zipCode' => $sender['zipCode'] ??  '',
                    'sender_address' => $sender_address,
                    'sender_detailAddress' => $sender_detailAddress,
                ];

                $parcel = json_decode($order->parcel,  true);
                $goodsList = $parcel['goodsList'];

                $features = $order->features;
                $taxId = '';
                if($features){
                    $features = json_decode($features,  true);
                    $taxId = $features['taxId'] ?? '';
                }

                $re = [];
                foreach ($goodsList as $item){
                    $lvgPaid = $item['extension']['lvgPaid'] ?? '';
                    $res = $base_data;
                    $res['weight'] = $parcel['weight'] ?? '';
                    $res['weightUnit'] = $parcel['weightUnit']  ;
                    $res['name'] = $item['name'] ??  '';
                    $res['localName'] = $item['localName'] ??  '';
                    $res['categoryName'] = $item['categoryName'] ??  '';
                    $res['price'] = $item['price'] ?? '';
                    $res['itemPrice'] = $item['itemPrice'] ?? '';
                    $res['priceUnit'] = $item['priceUnit'] ??  '';
                    $res['priceCurrency'] = $item['priceCurrency'] ?? '';
                    $res['quantity'] = $item['quantity'] ?? '';
                    $res['hsCode'] = $item['hsCode'] ??  '';
                    $res['declaredValue'] = $item['declaredValue'] ?? '';
                    $res['lvgPaid'] = $lvgPaid;
                    $res['taxId'] = $taxId;

                    $re[] = $res;
                }

                return $re;
            });

            if($list->isNotEmpty()){
                $list = $list->toArray();
                foreach ($list as $value){
                    $data = array_merge($data, $value);
                }
            }


        }

        return Excel::download(new BigTakeOrderManifestExport(collect($data)), 'manifest.xlsx');

    }

    public function manifest2(Request $request)
    {
        $take_order_ids = $request->input('ids', []);

        $data = [];
        foreach ($take_order_ids as $take_order_id){
            $take_order = TakeOrderModel::find($take_order_id);
            if(!$take_order){
                return $this->error('提单不存在');
            }

            $bigbagID = $take_order->notify->pluck('bigBagID');

            $orders = OrderModel::whereIn('bigBagID', $bigbagID)
                ->select('orderCode', 'receiver', 'sender', 'trackingNumber', 'bigBagID', 'fromLocation', 'toLocation', 'parcel', 'features')
                ->get();

            $transportNo = $take_order->flight_number;
            $sn = $take_order->sn;

//            $flight = $take_order->flight;
//            if($flight){
//                $item = $flight->items->first();
//                $transportNo = $item->air_line->flight_number ??  '';
//            }

            $list = $orders->map(function($order) use ($transportNo, $sn) {
                $receiver = json_decode($order->receiver,  true);
                $receiver_address = ''; $receiver_detailAddress = '';
                if($receiver['address']){
                    $receiver_detailAddress = $receiver['address']['detailAddress'] ??  '';
                    if(isset($receiver['address']['detailAddress'])){
                        unset($receiver['address']['detailAddress']);
                    }

                    $receiver_address = implode(' ', $receiver['address']);
                }

                $sender = json_decode($order->sender,  true);
                $sender_address = ''; $sender_detailAddress = '';
                if($sender['address']){
                    $sender_detailAddress = $sender['address']['detailAddress'] ??  '';
                    if(isset($sender['address']['detailAddress'])){
                        unset($sender['address']['detailAddress']);
                    }
                    $sender_address = implode(' ', $sender['address']);
                }

                $base_data = [
                    'orderCode' => $order->orderCode,
                    'trackingNumber' => $order->trackingNumber,
                    'bigBagID' => $order->bigBagID,
                    'transportNo' => $transportNo,
                    'mawbNumber' => $sn,
                    'fromLocation' => $order->fromLocation,
                    'toLocation' => $order->toLocation,
                    'receiver_name' => $receiver['name'] ??  '',
                    'receiver_phone' => $receiver['phone'] ??  '',
                    'receiver_mobile' => $receiver['mobile'] ??  '',
                    'receiver_email' => $receiver['email'] ??  '',
                    'receiver_zipCode' => $receiver['zipCode'] ??  '',
                    'receiver_address' => $receiver_address,
                    'receiver_detailAddress' => $receiver_detailAddress,
                    'sender_name' => $sender['name'] ??  '',
                    'sender_phone' => $sender['phone'] ??  '',
                    'sender_mobile' => $sender['mobile'] ??  '',
                    'sender_email' => $sender['email'] ??  '',
                    'sender_zipCode' => $sender['zipCode'] ??  '',
                    'sender_address' => $sender_address,
                    'sender_detailAddress' => $sender_detailAddress,
                ];

                $parcel = json_decode($order->parcel,  true);
                $goodsList = $parcel['goodsList'];

                $features = $order->features;
                $taxId = '';
                if($features){
                    $features = json_decode($features,  true);
                    $taxId = $features['taxId'] ?? '';
                }

                $re = [];
                $goods_num = count($goodsList);
                foreach ($goodsList as $item){
                    $lvgPaid = $item['extension']['lvgPaid'] ?? '';
                    $res = $base_data;
                    $res['weight'] = round($parcel['weight']/$goods_num, 2) ?? '';
                    $res['weightUnit'] = $parcel['weightUnit']  ;
                    $res['name'] = $item['name'] ??  '';
                    $res['localName'] = $item['localName'] ??  '';
                    $res['categoryName'] = $item['categoryName'] ??  '';
                    $res['price'] = $item['price'] ?? '';
                    $res['itemPrice'] = $item['itemPrice'] ?? '';
                    $res['priceUnit'] = $item['priceUnit'] ??  '';
                    $res['priceCurrency'] = $item['priceCurrency'] ?? '';
                    $res['quantity'] = $item['quantity'] ?? '';
                    $res['hsCode'] = $item['hsCode'] ??  '';
                    $res['declaredValue'] = $item['declaredValue'] ?? '';
                    $res['lvgPaid'] = $lvgPaid;
                    $res['taxId'] = $taxId;

                    $re[] = $res;
                }

                return $re;
            });

            if($list->isNotEmpty()){
                $list = $list->toArray();
                foreach ($list as $value){
                    $data = array_merge($data, $value);
                }
            }


        }

        return Excel::download(new BigTakeOrderManifestExport(collect($data)), 'manifest.xlsx');

    }

}
